/**
 * @filename HuJiao
 *
 * @module
 *
 * @author Justin <zhou78620051@126.com>
 * @version 1
 * @time 2015/10/18 8:37
 */

/**
 * 获取距离, 参考 WeChatAPIService.calcDistance
 */
function calcDistance(lat1, lng1, lat2, lng2, next) {
  if (typeof next != "function") {
    next = function () {
    };
  }

  var EARTH_RADIUS = 6378137.0;    //单位M
  var PI = Math.PI;

  function getRad(d) {
    return d * PI / 180.0;
  }

  /**
   * caculate the great circle distance 把地球当成圆球计算, 有误差
   * @param {Object} lat1
   * @param {Object} lng1
   * @param {Object} lat2
   * @param {Object} lng2
   */
  function getGreatCircleDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = getRad(lat1);
    var radLat2 = getRad(lat2);

    var a = radLat1 - radLat2;
    var b = getRad(lng1) - getRad(lng2);

    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000.0;

    return s;
  }

  /**
   * approx distance between two points on earth ellipsoid 把地球当成椭球计算, 较精确
   * @param {Object} lat1
   * @param {Object} lng1
   * @param {Object} lat2
   * @param {Object} lng2
   */
  function getFlatternDistance(lat1, lng1, lat2, lng2) {
    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    return d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
  }

  var distance = getFlatternDistance(lat1, lng1, lat2, lng2);
  next(null, distance);
  return distance;
}

wx.ready(function () {
  var voice = {
    localId: '',
    serverId: ''
  };

  function recordOver(res) {
    voice.localId = res.localId;
    document.querySelector('#voice-message').value = "点击录制消息";
    //alert("录音结束自动上传中...");
    wx.uploadVoice({
      localId: voice.localId,
      success: function (res) {
        // todo 声音上传结束, 在此处理显示问题
        alert('上传语音成功，serverId 为' + res.serverId);
        voice.serverId = res.serverId;
      }
    });
  }

  document.querySelector('#audio-btn').onclick = function () {
    $("#text-message").toggle();
    $("#voice-message").toggle();
  };
  document.querySelector('#voice-message').onmousedown = function () {
    document.querySelector('#voice-message').value = "录音中...";
    wx.startRecord({
      cancel: function () {
        alert('用户拒绝授权录音');
      }
    });
  };
  document.querySelector('#voice-message').onmouseup = function () {
    wx.stopRecord({
      success: function (res) {
        recordOver(res);
        //alert("录音结束");
      },
      fail: function (res) {
        //alert(JSON.stringify(res));
        alert("录制失败,请重新录制!");
      }
    });
  };
  wx.onVoiceRecordEnd({
    complete: function (res) {
      recordOver(res);
      //alert('录音时间已超过一分钟');
    }
  });

  var images = {
    localId: [],
    serverId: []
  };
  document.querySelector('#image-btn').onclick = function () {
    wx.chooseImage({
      success: function (res) {
        images.localId = res.localIds;
        //alert('已选择 ' + res.localIds.length + ' 张图片, 正在上传...');
        images.serverId = [];

        var i = 0;

        function upload() {
          wx.uploadImage({
            localId: images.localId[i],
            success: function (res) {
              i++;
              //alert('已上传：' + i + '/' + images.localId.length);
              images.serverId.push(res.serverId);
              if (i < images.localId.length) {
                upload();
              } else {
                // todo 图片上传结束, 在此处理显示问题
                alert("图片上传结束!");
                //alert(JSON.stringify(images));
              }
            },
            fail: function (res) {
              //alert(JSON.stringify(res));
              alert("图片上传失败!");
            }
          });
        }

        upload();
      }
    });
  };

  var location = null;  // {"longitude": 0,"latitude": 0,"accuracy": 0,"speed": -1,"errMsg": ""};
  wx.getLocation({
    success: function (res) {
      // todo 在此计算所有用户的地理位置距离
      alert(JSON.stringify(res));
      alert(pageinfo.nick_name);
      location = res;
    },
    cancel: function (res) {
      alert('用户拒绝授权获取地理位置');
    }
  });

  document.querySelector('#previewImage').onclick = function () {
    wx.previewImage({
      current: 'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
      urls: [
        'http://img3.douban.com/view/photo/photo/public/p2152117150.jpg',
        'http://img5.douban.com/view/photo/photo/public/p1353993776.jpg',
        'http://img3.douban.com/view/photo/photo/public/p2152134700.jpg'
      ]
    });
  };
});

wx.error(function (res) {
  //alert(res.errMsg);
});
